package x.ovo.wechat.bot.plugin;

import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.http.HttpUtil;
import org.dromara.hutool.http.server.SimpleServer;
import x.ovo.wechat.bot.core.Constant;
import x.ovo.wechat.bot.core.command.CommandExcutor;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.plugin.Plugin;

@Slf4j(topic = "HttpPlugin")
public class HttpPlugin extends Plugin {

    private SimpleServer server;

    @Override
    public void onLoad() {
        if (!FileUtil.exists(FileUtil.file(this.getDataDir(), Constant.Files.CONFIG_FILE_NAME))) {
            this.saveDefaultConfig();
        }
        Integer port = MapUtil.getInt(this.getConfig(), "server_port");
        String serverToken = StrUtil.defaultIfBlank(MapUtil.getStr(this.getConfig(), "server_token"), IdUtil.fastSimpleUUID());
        server = HttpUtil.createServer(port);
        HttpHelper.setPlugin(this);
        server.addFilter(HttpHelper.tokenFilter(serverToken));
        server.addAction("", HttpHelper.helpAction());
        server.addAction("sendText", HttpHelper.sendTextAction());
        server.addAction("sendImage", HttpHelper.sendImageAction());
        server.addAction("sendVideo", HttpHelper.sendVideoAction());
        server.addAction("sendFile", HttpHelper.sendFileAction());
        server.addAction("getSelf", HttpHelper.getSelfAction());
        server.addAction("getContact", HttpHelper.getContactAction());
        server.addAction("getGroupMember", HttpHelper.getGroupMemberAction());
        server.addAction("modifyGroupName", HttpHelper.modifyGroupNameAction());
        server.start();
        log.info("http服务启动成功，端口：{}, token: {}", port, serverToken);
    }

    @Override
    public void onUnload() {
        server.getRawServer().stop(0);
    }

    @Override
    public EventListener<?, ?> getEventListener() {
        return new HttpListener(this);
    }

    @Override
    public CommandExcutor getCommandExcutor() {
        return null;
    }
}
